<?php
namespace app\api\logic;


use think\exception\HttpResponseException;
use think\Request;
use think\Response;

class BaseLogic
{
    private static $instance;
    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';

    //获取对象单例
    public static function getInstance()
    {
        //判断$instance是否是对象，不是则创建
        if (!self::$instance instanceof static) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 操作失败返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param string $type   输出类型，支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];
        // 如果未设置类型则使用默认类型判断
        $type = $type ? : $this->responseType;

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

    // 条件处理
    public function dataHandleWhere($params)
    {
        $where = [];

        if (!empty($params['createtime'])) {
            $time = explode('-', $params['createtime']);
            $startTime = strtotime($time[0] . '-' . $time[1] . '-01 00:00:00');
           $endTime = strtotime('+1 month', $startTime) - 1;
            $where['createtime'] = ['between', [$startTime, $endTime]];
        }

        if (!empty($params['time'])) {
            $time = explode('-', $params['time']);
            $startTime = strtotime($time[0] . '-' . $time[1] . '-01 00:00:00');
           $endTime = strtotime('+1 month', $startTime) - 1;
            $where['time'] = ['between', [$startTime, $endTime]];
        }

        if (!empty($params['status'])){
            $where['status'] = $params['status'];
        }

        return $where;
    }


}